package eg.edu.eelu.fyp2013.jdetector.core.swt;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;

import javax.swing.Icon;

import matlabcontrol.MatlabConnectionException;
import matlabcontrol.MatlabInvocationException;
import matlabcontrol.MatlabProxy;
import matlabcontrol.MatlabProxyFactory;
import matlabcontrol.extensions.MatlabNumericArray;
import matlabcontrol.extensions.MatlabTypeConverter;

public class Chain {
	
	public BufferedImage performChain(BufferedImage OrignalImage)throws MatlabConnectionException, MatlabInvocationException{
		
		    //Create a proxy, which we will use to control MATLAB
		    MatlabProxyFactory factory = new MatlabProxyFactory();
		    MatlabProxy proxy = factory.getProxy();
		    int tempPixelColor = 0 ;
		    int w = OrignalImage.getWidth();
		    int h = OrignalImage.getHeight();
		    double [][] redmatrix = new double [w][h];
		    double [][] greenmatrix = new double [w][h];
		    double [][] bluematrix = new double [w][h];
		    
		    for(int i = 0 ; i < h; i++)
		    {
		    	for(int j = 0; j < w ; j++)
		    	{
		    		 tempPixelColor = OrignalImage.getRGB(j, i);
		    		 int red = (0xFF & tempPixelColor>>16);
		    		 redmatrix[i][j] = red;
		    		 int green = (0xFF & tempPixelColor>>8);
		    		 greenmatrix[i][j] = green;
		    		 int blue = (0xFF & tempPixelColor);
		    		 bluematrix[i][j] = blue;
		    		 
		    	}
		    }
		    
		    MatlabTypeConverter processor = new MatlabTypeConverter(proxy);
		    processor.setNumericArray("red", new MatlabNumericArray(redmatrix,null));
		    processor.setNumericArray("green", new MatlabNumericArray(greenmatrix,null));
		    processor.setNumericArray("blue", new MatlabNumericArray(bluematrix,null));
		    proxy.eval("[chainFilters] = chain(red,green,blue)");
		    double [][] chinvalues = processor.getNumericArray("chainFilters").getRealArray2D();
		    
		    BufferedImage Output = new BufferedImage(256, 256, BufferedImage.TYPE_INT_RGB);
		    
		    for(int i = 0 ; i < Output.getWidth(); i++)
		    {
		    	for(int  j = 0; j < Output.getHeight(); j++)
		    	{
		    		int rgb = (int)chinvalues[i][j]<< 16 | (int) chinvalues[i][j] << 8 | (int) chinvalues[i][j];
		    		Output.setRGB(j, i, rgb);
		    		
		    	}
		    }
		    proxy.disconnect();
		    return Output;
		
	}
	
    
}
